#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'tian'
__data__ = '2021/12/4 16:56'
# software: PyCharm


from django.shortcuts import render, HttpResponse, redirect, reverse
from django.http import JsonResponse

from django.views import View

from apps.app01 import models
from apps.app01.forms.mymodelform import ItModelForm

from apps.app01.templatetags.page import Pagination


# Create your views here.
def default_page(request):
    """
    系统进入默认页面
    :param request:
    :return:
    """
    if request.method == "GET":
        project_list = models.It.objects.order_by("-pk")
        return render(request, "default_page.html", {"project_dict": project_list})
    return HttpResponse("OK")


class Index(View):
    """
    项目首页
    """
    template_name = "index.html"

    def get_context(self):
        return models.It.get_all()

    def get(self, request, *args, **kwargs):
        """
        处理get请求的逻辑
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        it_obj_count = self.get_context()  # 项目表中共有多少项目
        current_page = request.GET.get("page")
        base_url = reverse("index")

        paginator = Pagination(current_page=current_page, all_count=it_obj_count, base_url=base_url,
                               query_params=request.GET.copy())
        data_list = models.It.objects.all().order_by("-pk")[paginator.start:paginator.end]
        it_form_obj = ItModelForm()  # form组件
        context = {
            "form": it_form_obj,
            "page": paginator,
            "all_count": it_obj_count,
            "it_obj": data_list,
        }
        return render(request, self.template_name, context)

    def post(self, request):
        """
        添加项目
        :param request:
        :return:
        """
        # 添加项目 & 修改项目
        fid = request.POST.get("fid", "")
        edit_it_object = None
        if fid.isdecimal():
            edit_it_object = models.It.objects.filter(pk=fid).first()
        if edit_it_object:
            # 编辑项目
            form_data = ItModelForm(request.POST, instance=edit_it_object)
        else:
            # 新增项目
            form_data = ItModelForm(data=request.POST)
        if form_data.is_valid():
            form_data.save()
            return JsonResponse({"status": True, "data": reverse("index")})
        return JsonResponse({"status": False, "error": form_data.errors})


def search(request):
    """
    搜索
    :param request:
    :return:
    """
    key = request.POST.get("search_key", "").strip()
    if key:
        it_obj = models.It.objects.filter(it_name__icontains=key)
        it_form_obj = ItModelForm()
        if it_obj:
            return render(request, "index.html", {"it_obj": it_obj, "search_key": key, "form": it_form_obj})
        else:
            return render(request, "index.html", {"it_obj": it_obj, "search_key": key, "form": it_form_obj})
    return redirect("index")


def delete_it(request):
    """
    删除项目表记录，pk：项目的Pk
    :param request:
    :param pk:
    :return:
    """
    pk = request.POST.get("tid")
    try:
        if request.method == "POST":
            models.It.objects.filter(pk=pk).delete()
            return JsonResponse({"status": True})
    except Exception:
        return ({"status": False, "error": "删除失败"})
    return JsonResponse({"status": False, "error": "删除post请求,非法"})
